package com.zh.mediaservice.AiBigModel;

import com.zh.mediacommon.constant.BigModeHttpConstant;
import com.zh.mediacommon.constant.MessageConstant;
import com.zh.mediacommon.ecxeption.AIModelException;
import com.zh.mediaservice.config.XfXhConfig;
import okhttp3.*;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class SparkLIte {
    @Autowired
    private XfXhConfig xfXhConfig;
    public boolean  getIsMediaQuestion(String question) {
        // 创建OkHttpClient实例
        OkHttpClient client = new OkHttpClient();

        // 创建JSON数据
        JSONObject jsonData = new JSONObject();
        jsonData.put(BigModeHttpConstant.MODEL, xfXhConfig.getDomain2());

        JSONObject message = new JSONObject();
        message.put(BigModeHttpConstant.ROLE, BigModeHttpConstant.USER);
        message.put(BigModeHttpConstant.CONTENT,BigModeHttpConstant.QUESTION+question);

        JSONArray messages = new JSONArray();
        messages.put(message);

        jsonData.put(BigModeHttpConstant.MESSAGES, messages);

        // 创建请求体
        RequestBody body = RequestBody.create(jsonData.toString(), MediaType.parse(BigModeHttpConstant.APPLICATION_JSON));

        // 构建请求
        Request request = new Request.Builder()
                .url(xfXhConfig.getHostUrl2())
                .post(body)
                .addHeader(BigModeHttpConstant.CONTENT_TYPE, BigModeHttpConstant.APPLICATION_JSON)
                .addHeader(BigModeHttpConstant.AUTHORIZATION, BigModeHttpConstant.BEARER + xfXhConfig.getApiPassword())
                .build();
        String content="1";
        try (Response response = client.newCall(request).execute()) {
            if (response.isSuccessful()) {
                String responseBody = response.body().string();
                JSONObject jsonObject = new JSONObject(responseBody);
                JSONArray choicesArray = jsonObject.getJSONArray(BigModeHttpConstant.CHOICES);
                JSONObject firstChoice = choicesArray.getJSONObject(0);
                JSONObject messageObject = firstChoice.getJSONObject(BigModeHttpConstant.MESSAGE);
                content = messageObject.getString(BigModeHttpConstant.CONTENT);
            } else {
                throw new AIModelException(BigModeHttpConstant.ERROR);
            }
        } catch (IOException e) {
            throw new AIModelException(MessageConstant.UNKNOWN_ERROR);
        }
        System.out.println("回答" +" " +content);
        if(content.contains(BigModeHttpConstant.IS_NOT_MEDIA))
            return false;
        else
            return true;
    }
}
